#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;

class Point
: public std::enable_shared_from_this<Point>
{
public:
    Point(int x,int y)
    : _ix(x)
    , _iy(y)
    {
        cout << "Point(int,int)" << endl;
    }

    //1.
    /* Point * addPoint(Point * pt){ */
    /*     _ix += pt->_ix; */
    /*     _iy += pt->_iy; */
    /*     return this; */
    /* } */

    //2.
    /* shared_ptr<Point> addPoint(Point * pt){ */
    /*     _ix += pt->_ix; */
    /*     _iy += pt->_iy; */
    /*     //return语句中创建的匿名的shared_ptr对象依然与sp共用了裸指针 */
    /*     //error */
    /*     return shared_ptr<Point>(this); */

    /*     //利用sp管理的Point对象的数据成员重新创建一个Point资源 */
    /*     //交给新的智能指针进行管理 */
    /*     //ok */
    /*     /1* return shared_ptr<Point>(new Point(_ix,_iy)); *1/ */
    /* } */

    //3.
    shared_ptr<Point> addPoint(Point * pt){
        _ix += pt->_ix;
        _iy += pt->_iy;
        //合法的方式获得一个共享*this资源的shared_ptr
        return shared_from_this();
    }
    

    void print(){
        cout << "(" << _ix
            << "," << _iy
            << ")" << endl;
    }

    ~Point(){
        cout << "~Point()" << endl;
    }
private:
    int _ix;
    int _iy;
};

void test0(){
    shared_ptr<Point> sp(new Point(1,2));
    shared_ptr<Point> sp2(new Point(3,4));

    //1.
    //这种情况实际上是sp3与sp共用了一个裸指针进行创建
    /* shared_ptr<Point> sp3(sp->addPoint(sp2.get())); */
    /* cout << "sp3 = "; */
    /* sp3->print(); */


    //2.
    /* shared_ptr<Point> sp3(sp->addPoint(sp2.get())); */
    /* cout << "sp3 = "; */
    /* sp3->print(); */
    /* cout << sp.get() << endl; */
    /* cout << sp3.get() << endl; */

    //3.
    shared_ptr<Point> sp3(sp->addPoint(sp2.get()));
    cout << "sp3 = ";
    sp3->print();
    cout << sp.get() << endl;
    cout << sp3.get() << endl;
}

int main(void){
    test0();
    return 0;
}
